<template>
  <div class="search-question-view">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">题目搜索</h1>
      <p class="page-subtitle">查找历年公务员考试真题及解析</p>
    </div>

    <!-- 题库搜索 -->
    <template v-if="contentMode === 'search'">
      <!-- 搜索区域 -->
      <div class="search-section">
        <div class="search-form">
          <el-input
            v-model="searchKeyword"
            placeholder="输入关键词搜索题目"
            suffix-icon="Search"
            class="search-input"
          />
          <el-button type="primary" @click="handleSearch" class="search-button">搜索</el-button>
        </div>

        <!-- 筛选条件 -->
        <div class="filter-section">
          <el-form :inline="true" :model="filterForm" class="filter-form">
            <el-form-item label="题目类型">
              <el-select v-model="filterForm.questionType" placeholder="请选择题目类型">
                <el-option label="全部" value="" />
                <el-option label="单选题" value="single_choice" />
                <el-option label="多选题" value="multiple_choice" />
                <el-option label="判断题" value="true_false" />
                <el-option label="填空题" value="blank_filling" />
                <el-option label="简答题" value="short_answer" />
              </el-select>
            </el-form-item>
            <el-form-item label="难度">
              <el-select v-model="filterForm.difficulty" placeholder="请选择难度">
                <el-option label="全部" value="" />
                <el-option label="简单" value="easy" />
                <el-option label="中等" value="medium" />
                <el-option label="困难" value="hard" />
              </el-select>
            </el-form-item>
            <el-form-item label="分类">
              <el-select v-model="filterForm.category" placeholder="请选择分类">
                <el-option label="全部" value="" />
                <el-option label="法律常识" value="1" />
                <el-option label="时政热点" value="2" />
                <el-option label="言语理解" value="3" />
                <el-option label="数量关系" value="4" />
                <el-option label="判断推理" value="5" />
                <el-option label="资料分析" value="6" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button @click="resetFilter">重置筛选</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>

      <!-- 题目列表 -->
      <div class="questions-section">
        <div class="questions-header">
          <div class="questions-info">
            <span class="questions-count">共找到 {{ questions.length }} 道题目</span>
          </div>
          <div class="sort-options">
            <el-select v-model="sortBy" placeholder="排序方式">
              <el-option label="默认排序" value="default" />
              <el-option label="难度从高到低" value="difficulty_desc" />
              <el-option label="难度从低到高" value="difficulty_asc" />
              <el-option label="正确率从高到低" value="correct_rate_desc" />
              <el-option label="正确率从低到高" value="correct_rate_asc" />
            </el-select>
          </div>
        </div>

        <div class="questions-list">
          <QuestionCard 
            v-for="question in questions" 
            :key="question.id"
            :question="question"
            :show-answer="false"
            :show-stats="true"
            :can-favorite="true"
            class="mb-4"
          />
        </div>

        <!-- 空状态 -->
        <div v-if="questions.length === 0" class="empty-state">
          <el-empty description="没有找到相关题目，请尝试其他关键词或筛选条件"></el-empty>
        </div>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalQuestions"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </template>

    <!-- 题目分类 -->
    <template v-else-if="contentMode === 'categories'">
      <div class="section-title">
        <h2>题目分类</h2>
        <p>按类别浏览不同类型的题目</p>
      </div>
      
      <div class="categories-section">
        <div class="category-card" v-for="category in questionCategories" :key="category.id">
          <div class="category-icon">
            <el-icon><component :is="category.icon" /></el-icon>
          </div>
          <div class="category-info">
            <h3>{{ category.name }}</h3>
            <p>{{ category.count }} 个题目</p>
          </div>
        </div>
      </div>
    </template>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { useRoute } from 'vue-router';
import QuestionCard from '@/components/QuestionCard.vue';

const route = useRoute();

// 搜索关键词
const searchKeyword = ref('');

// 筛选表单
const filterForm = ref({
  questionType: '',
  difficulty: '',
  category: ''
});

// 排序方式
const sortBy = ref('default');

// 分页数据
const currentPage = ref(1);
const pageSize = ref(10);
const totalQuestions = ref(100);

// 根据路由路径决定显示的内容类型
const contentMode = computed(() => {
  const path = route.path;
  if (path.includes('/categories')) return 'categories';
  return 'search';
});

// 题目分类数据
const questionCategories = computed(() => {
  const categories = [
    {
      id: 'xingce',
      name: '行测',
      count: mockQuestions.value.filter(q => q.category?.name.includes('行测') || ['数量关系', '判断推理', '资料分析', '言语理解'].includes(q.category?.name || '')).length,
      icon: 'BarChart'
    },
    {
      id: 'shenlun',
      name: '申论',
      count: mockQuestions.value.filter(q => q.category?.name.includes('申论')).length,
      icon: 'FileText'
    },
    {
      id: 'mianshi',
      name: '面试',
      count: mockQuestions.value.filter(q => q.category?.name.includes('面试')).length,
      icon: 'User'
    },
    {
      id: 'common-sense',
      name: '常识判断',
      count: mockQuestions.value.filter(q => q.category?.name.includes('法律常识') || q.category?.name.includes('时政热点')).length,
      icon: 'Star'
    },
    {
      id: 'verbal',
      name: '言语理解',
      count: mockQuestions.value.filter(q => q.category?.name.includes('言语理解')).length,
      icon: 'Document'
    },
    {
      id: 'logic',
      name: '判断推理',
      count: mockQuestions.value.filter(q => q.category?.name.includes('判断推理')).length,
      icon: 'Box'
    },
    {
      id: 'math',
      name: '数量关系',
      count: mockQuestions.value.filter(q => q.category?.name.includes('数量关系')).length,
      icon: 'Calculator'
    },
    {
      id: 'data',
      name: '资料分析',
      count: mockQuestions.value.filter(q => q.category?.name.includes('资料分析')).length,
      icon: 'PieChart'
    }
  ];
  return categories;
});

// 模拟题目数据
const mockQuestions = ref([
  {
    id: 1,
    text: '下列选项中，属于我国宪法规定的公民基本权利的是（ ）',
    type: 'single_choice',
    difficulty: 'medium',
    category: { id: 1, name: '法律常识', status: 'active' },
    options: [
      { id: 1, questionId: 1, content: '选举权和被选举权', isCorrect: true, order: 1 },
      { id: 2, questionId: 1, content: '罢工自由', isCorrect: false, order: 2 },
      { id: 3, questionId: 1, content: '迁徙自由', isCorrect: false, order: 3 },
      { id: 4, questionId: 1, content: '私有财产神圣不可侵犯', isCorrect: false, order: 4 }
    ],
    explanation: '根据我国宪法规定，公民的基本权利包括选举权和被选举权、言论自由、宗教信仰自由等。罢工自由和迁徙自由未被明确规定为基本权利，私有财产神圣不可侵犯是资本主义国家宪法的常见表述。',
    stats: {
      totalAttempts: 1256,
      correctRate: 0.78
    }
  },
  {
    id: 2,
    text: '2023年中央经济工作会议指出，做好2024年经济工作，要坚持稳中求进工作总基调，完整、准确、全面贯彻新发展理念，加快构建新发展格局，着力推动高质量发展。下列不属于新发展理念的是（ ）',
    type: 'single_choice',
    difficulty: 'easy',
    category: { id: 2, name: '时政热点', status: 'active' },
    options: [
      { id: 5, questionId: 2, content: '创新', isCorrect: false, order: 1 },
      { id: 6, questionId: 2, content: '协调', isCorrect: false, order: 2 },
      { id: 7, questionId: 2, content: '绿色', isCorrect: false, order: 3 },
      { id: 8, questionId: 2, content: '开放', isCorrect: false, order: 4 },
      { id: 9, questionId: 2, content: '共享', isCorrect: false, order: 5 },
      { id: 10, questionId: 2, content: '均衡', isCorrect: true, order: 6 }
    ],
    explanation: '新发展理念包括创新、协调、绿色、开放、共享五大发展理念，均衡不属于新发展理念。',
    stats: {
      totalAttempts: 987,
      correctRate: 0.85
    }
  },
  {
    id: 3,
    text: '下列句子中，没有语病的一项是（ ）',
    type: 'single_choice',
    difficulty: 'medium',
    category: { id: 3, name: '言语理解', status: 'active' },
    options: [
      { id: 11, questionId: 3, content: '通过这次学习，使我提高了对环保重要性的认识。', isCorrect: false, order: 1 },
      { id: 12, questionId: 3, content: '我们要认真克服并随时发现自己的缺点。', isCorrect: false, order: 2 },
      { id: 13, questionId: 3, content: '是否具有良好的心理素质，是考试取得好成绩的关键。', isCorrect: false, order: 3 },
      { id: 14, questionId: 3, content: '在老师的帮助下，他很快有了进步。', isCorrect: true, order: 4 }
    ],
    explanation: '选项A缺少主语，应去掉"通过"或"使"；选项B语序不当，应先"发现"再"克服"；选项C两面对一面，应去掉"是否"。',
    stats: {
      totalAttempts: 1567,
      correctRate: 0.72
    }
  },
  {
    id: 4,
    text: '某单位组织员工去旅游，共有36人报名参加。已知大客车每辆可坐50人，租金为500元；小客车每辆可坐30人，租金为300元。请问怎样租车最省钱？（ ）',
    type: 'single_choice',
    difficulty: 'hard',
    category: { id: 4, name: '数量关系', status: 'active' },
    options: [
      { id: 15, questionId: 4, content: '1辆大客车', isCorrect: false, order: 1 },
      { id: 16, questionId: 4, content: '2辆小客车', isCorrect: false, order: 2 },
      { id: 17, questionId: 4, content: '1辆大客车和1辆小客车', isCorrect: false, order: 3 },
      { id: 18, questionId: 4, content: '1辆小客车', isCorrect: true, order: 4 }
    ],
    explanation: '36人只需要1辆小客车即可，租金为300元，比其他方案更省钱。',
    stats: {
      totalAttempts: 876,
      correctRate: 0.65
    }
  },
  {
    id: 5,
    text: '根据《中华人民共和国民法典》规定，自然人下落不明满（ ）年的，利害关系人可以向人民法院申请宣告该自然人为失踪人。',
    type: 'single_choice',
    difficulty: 'easy',
    category: { id: 1, name: '法律常识', status: 'active' },
    options: [
      { id: 19, questionId: 5, content: '1年', isCorrect: false, order: 1 },
      { id: 20, questionId: 5, content: '2年', isCorrect: true, order: 2 },
      { id: 21, questionId: 5, content: '3年', isCorrect: false, order: 3 },
      { id: 22, questionId: 5, content: '4年', isCorrect: false, order: 4 }
    ],
    explanation: '《中华人民共和国民法典》第四十条规定，自然人下落不明满二年的，利害关系人可以向人民法院申请宣告该自然人为失踪人。',
    stats: {
      totalAttempts: 2345,
      correctRate: 0.91
    }
  },
  {
    id: 6,
    text: '下列哪些属于公务员法规定的公务员义务？（ ）',
    type: 'multiple_choice',
    difficulty: 'medium',
    category: { id: 1, name: '法律常识', status: 'active' },
    options: [
      { id: 23, questionId: 6, content: '忠于宪法，模范遵守、自觉维护宪法和法律', isCorrect: true, order: 1 },
      { id: 24, questionId: 6, content: '忠于国家，维护国家的安全、荣誉和利益', isCorrect: true, order: 2 },
      { id: 25, questionId: 6, content: '忠于人民，全心全意为人民服务，接受人民监督', isCorrect: true, order: 3 },
      { id: 26, questionId: 6, content: '具有良好的政治素质和道德品行', isCorrect: true, order: 4 }
    ],
    explanation: '根据《中华人民共和国公务员法》第十四条规定，公务员应当履行下列义务：（一）忠于宪法，模范遵守、自觉维护宪法和法律，自觉接受中国共产党领导；（二）忠于国家，维护国家的安全、荣誉和利益；（三）忠于人民，全心全意为人民服务，接受人民监督；（四）忠于职守，勤勉尽责，服从和执行上级依法作出的决定和命令，按照规定的权限和程序履行职责，努力提高工作质量和效率；（五）保守国家秘密和工作秘密；（六）带头践行社会主义核心价值观，坚守法治，遵守纪律，恪守职业道德，模范遵守社会公德、家庭美德；（七）清正廉洁，公道正派；（八）法律规定的其他义务。',
    stats: {
      totalAttempts: 1678,
      correctRate: 0.68
    }
  },
  {
    id: 7,
    text: '2024年全国两会期间，政府工作报告指出，要坚持稳中求进工作总基调，完整、准确、全面贯彻新发展理念，加快构建新发展格局，着力推动高质量发展。2024年我国国内生产总值增长预期目标为（ ）左右。',
    type: 'single_choice',
    difficulty: 'easy',
    category: { id: 2, name: '时政热点', status: 'active' },
    options: [
      { id: 27, questionId: 7, content: '5%', isCorrect: true, order: 1 },
      { id: 28, questionId: 7, content: '6%', isCorrect: false, order: 2 },
      { id: 29, questionId: 7, content: '5.5%', isCorrect: false, order: 3 },
      { id: 30, questionId: 7, content: '4.5%', isCorrect: false, order: 4 }
    ],
    explanation: '2024年政府工作报告指出，2024年我国国内生产总值增长预期目标为5%左右。',
    stats: {
      totalAttempts: 1123,
      correctRate: 0.78
    }
  },
  {
    id: 8,
    text: '下列句子中，标点符号使用正确的一项是（ ）',
    type: 'single_choice',
    difficulty: 'medium',
    category: { id: 3, name: '言语理解', status: 'active' },
    options: [
      { id: 31, questionId: 8, content: '参加今天大会的有：工人、农民、知识分子、解放军和少先队员。', isCorrect: false, order: 1 },
      { id: 32, questionId: 8, content: '他说："我明天去北京开会。"', isCorrect: true, order: 2 },
      { id: 33, questionId: 8, content: '这个问题怎么解决呢？他想了想。说："还是先去请教老师吧。"', isCorrect: false, order: 3 },
      { id: 34, questionId: 8, content: '小明说，他很喜欢《西游记》这本书？', isCorrect: false, order: 4 }
    ],
    explanation: '选项A中的冒号多余，应去掉；选项C中"他想了想"后面的句号应改为逗号；选项D中句子末尾的问号应改为句号。',
    stats: {
      totalAttempts: 1876,
      correctRate: 0.65
    }
  },
  {
    id: 9,
    text: '某商场进行促销活动，一件上衣原价200元，现在打八折销售，请问现价是多少元？（ ）',
    type: 'single_choice',
    difficulty: 'easy',
    category: { id: 4, name: '数量关系', status: 'active' },
    options: [
      { id: 35, questionId: 9, content: '160元', isCorrect: true, order: 1 },
      { id: 36, questionId: 9, content: '180元', isCorrect: false, order: 2 },
      { id: 37, questionId: 9, content: '140元', isCorrect: false, order: 3 },
      { id: 38, questionId: 9, content: '120元', isCorrect: false, order: 4 }
    ],
    explanation: '打八折意味着现价是原价的80%，所以现价=200×80%=160元。',
    stats: {
      totalAttempts: 2109,
      correctRate: 0.95
    }
  },
  {
    id: 10,
    text: '根据《中华人民共和国刑法》规定，已满（ ）周岁的人犯罪，应当负刑事责任。',
    type: 'single_choice',
    difficulty: 'medium',
    category: { id: 1, name: '法律常识', status: 'active' },
    options: [
      { id: 39, questionId: 10, content: '14周岁', isCorrect: false, order: 1 },
      { id: 40, questionId: 10, content: '16周岁', isCorrect: true, order: 2 },
      { id: 41, questionId: 10, content: '18周岁', isCorrect: false, order: 3 },
      { id: 42, questionId: 10, content: '20周岁', isCorrect: false, order: 4 }
    ],
    explanation: '《中华人民共和国刑法》第十七条规定，已满十六周岁的人犯罪，应当负刑事责任。已满十四周岁不满十六周岁的人，犯故意杀人、故意伤害致人重伤或者死亡、强奸、抢劫、贩卖毒品、放火、爆炸、投放危险物质罪的，应当负刑事责任。',
    stats: {
      totalAttempts: 1567,
      correctRate: 0.82
    }
  }
]);

// 根据筛选条件和排序方式处理题目列表
const questions = computed(() => {
  let filteredQuestions = [...mockQuestions.value];
  
  // 根据关键词筛选
  if (searchKeyword.value) {
    filteredQuestions = filteredQuestions.filter(question => 
      question.text.includes(searchKeyword.value) ||
      (question.category && question.category.name.includes(searchKeyword.value))
    );
  }
  
  // 根据题目类型筛选
  if (filterForm.value.questionType) {
    filteredQuestions = filteredQuestions.filter(question => 
      question.type === filterForm.value.questionType
    );
  }
  
  // 根据难度筛选
  if (filterForm.value.difficulty) {
    filteredQuestions = filteredQuestions.filter(question => 
      question.difficulty === filterForm.value.difficulty
    );
  }
  
  // 根据分类筛选
  if (filterForm.value.category) {
    filteredQuestions = filteredQuestions.filter(question => 
      question.category && question.category.id.toString() === filterForm.value.category
    );
  }
  
  // 根据排序方式排序
  switch (sortBy.value) {
    case 'difficulty_desc':
      const difficultyOrder: Record<string, number> = { hard: 3, medium: 2, easy: 1 };
      filteredQuestions.sort((a, b) => (difficultyOrder[b.difficulty] || 0) - (difficultyOrder[a.difficulty] || 0));
      break;
    case 'difficulty_asc':
      filteredQuestions.sort((a, b) => (difficultyOrder[a.difficulty] || 0) - (difficultyOrder[b.difficulty] || 0));
      break;
    case 'correct_rate_desc':
      filteredQuestions.sort((a, b) => (b.stats?.correctRate || 0) - (a.stats?.correctRate || 0));
      break;
    case 'correct_rate_asc':
      filteredQuestions.sort((a, b) => (a.stats?.correctRate || 0) - (b.stats?.correctRate || 0));
      break;
    default:
      break;
  }
  
  return filteredQuestions;
});

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1; // 搜索时重置为第一页
};

// 重置筛选条件
const resetFilter = () => {
  filterForm.value = {
    questionType: '',
    difficulty: '',
    category: ''
  };
  searchKeyword.value = '';
  currentPage.value = 1;
};

// 分页大小变化处理
const handleSizeChange = (size: number) => {
  pageSize.value = size;
};

// 页码变化处理
const handleCurrentChange = (current: number) => {
  currentPage.value = current;
};
</script>

<style lang="scss" scoped>
  @import "element-plus/dist/index.css";
.search-question-view {
  padding: 20px;
  padding-top: 100px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  text-align: center;
  margin-bottom: 40px;
  padding: 40px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  color: white;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);

  .page-title {
    font-size: 2.5rem;
    font-weight: 700;
    margin-bottom: 10px;
  }

  .page-subtitle {
    font-size: 1.2rem;
    opacity: 0.9;
  }
}

.search-section {
  margin-bottom: 30px;

  .search-form {
    display: flex;
    gap: 10px;
    margin-bottom: 20px;

    .search-input {
      flex: 1;
      max-width: 800px;
    }

    .search-button {
      min-width: 100px;
    }
  }

  .filter-section {
    background-color: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

    .filter-form {
      .el-form-item {
        margin-right: 20px;
        margin-bottom: 0;

        .el-select {
          min-width: 120px;
        }
      }
    }
  }
}

.questions-section {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

  .questions-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #e2e8f0;

    .questions-info {
      .questions-count {
        font-size: 16px;
        color: #666;
      }
    }

    .sort-options {
      .el-select {
        min-width: 150px;
      }
    }
  }

  .questions-list {
    display: flex;
    flex-direction: column;
    gap: 20px;
  }

  .pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #e2e8f0;

  .el-pagination {
    .el-pager li {
      margin: 0 4px;
      min-width: 32px;
      height: 32px;
      line-height: 32px;
      font-size: 14px;
    }
  }
}

.section-title {
  text-align: center;
  margin-bottom: 30px;
  padding: 20px;
  background-color: #f8fafc;
  border-radius: 8px;
  
  h2 {
    font-size: 2rem;
    font-weight: 600;
    margin-bottom: 5px;
    color: #1e293b;
  }
  
  p {
    font-size: 1.1rem;
    color: #64748b;
  }
}

.categories-section {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  padding: 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.category-card {
  display: flex;
  align-items: center;
  padding: 20px;
  border-radius: 8px;
  border: 1px solid #e2e8f0;
  transition: all 0.3s ease;
  
  &:hover {
    border-color: #3b82f6;
    box-shadow: 0 4px 12px rgba(59, 130, 246, 0.1);
    transform: translateY(-2px);
  }
}

.category-icon {
  width: 50px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f0f9ff;
  color: #3b82f6;
  border-radius: 50%;
  margin-right: 15px;
  font-size: 24px;
}

.category-info h3 {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 5px;
  color: #1e293b;
}

.category-info p {
  font-size: 14px;
  color: #64748b;
}

.empty-state {
  text-align: center;
  padding: 40px;
  background-color: #f8fafc;
  border-radius: 8px;
  margin-top: 20px;
}
}
</style>